package com.cff.action.suggest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cff.domain.User;
import com.cff.domain.UserTask;
import com.cff.domain.UserType;
import com.cff.service.suggest.SuggestService;
import com.cff.service.user.UserService;
import com.cff.util.StringUtil;

import net.sf.json.JSONObject;

@Controller("suggestController")
@RequestMapping("/suggest")
public class SuggestAction {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private TaskService taskService;
  
	@Autowired
	private RepositoryService repositoryService;
	
	@Autowired
	private HistoryService historyService;
	
	@Autowired
	private SuggestService suggestService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/createtask")
	public void createTask(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		String type = request.getParameter("type");
		String title = request.getParameter("title");
		String taskType = request.getParameter("questiontype");
		String content = request.getParameter("content");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String mobile = request.getParameter("mobile");
		logger.info("createTask请求参参数{}"+type+"--" +taskType+ "--" +content+ "---" +name + "--" +email+ "--" +mobile);
		String mapResult = "200";
		try{
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("productAdvice");
			Task tmp = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
			String tmpTaskType = convertType(taskType);
			UserTask userTask = new UserTask();
			userTask.setTaskid(processInstance.getProcessInstanceId());
			userTask.setContent(content);
			userTask.setEmail(email);
			userTask.setMobile(mobile);
			userTask.setName(name);
			userTask.setTasktype(tmpTaskType);
			userTask.setType("01");
			userTask.setTitle(title);
			
			HttpSession session = request.getSession(false);
			User userInfo = (User) session.getAttribute("userInfo");
			String userid = "00000000";
			if(userInfo != null && !StringUtil.isEmpty(userInfo.getLoginId())){
				userid = userInfo.getLoginId();
			}
			tmp.setAssignee(userid);
		    taskService.complete(tmp.getId());
		    
		    userTask.setUserid(userid);
		    suggestService.save(userTask);
		}catch(Exception e){
			mapResult = "100";
		}
		
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("status",mapResult);
		
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/applylist")
	public void applyList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(false);
		User userInfo = (User) session.getAttribute("userInfo");
		String userid = "00000000";
		if(userInfo != null && !StringUtil.isEmpty(userInfo.getLoginId())){
			userid = userInfo.getLoginId();
		}
		List<UserTask> tasks = suggestService.getUserTask(userid);
		for(int i =0 ;i < tasks.size();i++){
			UserTask tmp = tasks.get(i);
			tmp.setTasktype(convertToType(tmp.getTasktype()));
			tmp.setCurviewer(tmp.getCurviewer() == null ? "" : tmp.getCurviewer());
		}
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("tasks",tasks);
		
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/waitlist")
	public void waitList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(false);
		User userInfo = (User) session.getAttribute("userInfo");
		String userid = "00000000";
		if(userInfo != null && !StringUtil.isEmpty(userInfo.getLoginId())){
			userid = userInfo.getLoginId();
		}
		String userType = userService.findUserType(userid);
		logger.info("准备查询userType为{}的任务",userType);
		System.out.println("准备查询userType为"+userType+"的任务");
		List<Task> tasks = taskService.createTaskQuery().taskName(userType).orderByTaskCreateTime().asc().list();
		List<UserTask> utasks = new ArrayList<UserTask>();
		for(int i=0;i<tasks.size(); i++){
			UserTask userTaskTmp = suggestService.getUserTaskByTaskId(tasks.get(i).getProcessInstanceId());
			if(userTaskTmp!=null){
				userTaskTmp.setRealTaskId(tasks.get(i).getId());
				utasks.add(userTaskTmp);
			}
		}
		
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("tasks",utasks);
		
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/processcommit")
	public synchronized void processCommit(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		String taskid = request.getParameter("taskid");
		String processid = request.getParameter("processid");
		logger.info("审批taskid：{},processid:{}",taskid,processid);
		HashMap<String,Object> map = new HashMap<String, Object>();
		String result = "200";

		try{
			UserTask userTask = suggestService.getUserTaskByTaskId(processid);
			int tmpStatus = Integer.parseInt(userTask.getStatus());
			taskService.complete(taskid);
			userTask.setStatus((tmpStatus+1)+"");
			suggestService.updateStatus(userTask);
		}catch(Exception e){
			result="100";
		}
		map.put("status",result);
		
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}

	public String convertType(String type){
		if("基础服务".equals(type)){
			return "01";
		}
		if("技术支持".equals(type)){
			return "02";
		}
		if("产品申请".equals(type)){
			return "03";
		}
		if("会议申请".equals(type)){
			return "04";
		}
		else
			return "05";
		
	}
	
	public String convertToType(String name){
		if("01".equals(name)){
			return "基础服务";
		}
		if("02".equals(name)){
			return "技术支持";
		}
		if("03".equals(name)){
			return "产品申请";
		}
		if("04".equals(name)){
			return "会议申请";
		}
		else
			return "其他";
		
	}
}
